
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList();
        //1.排序
        Arrays.sort(nums);
        //2.利用双指针解决问题
        for (int i = 0; i < nums.length ; ) {
            //固定数a
            if (nums[i] >= 0) {
                break;
            }
            int left = i + 1,right = nums.length - 1;

            while (left < right){
                int sum = nums[left] + nums[right];
                if (sum > -nums[i]) {
                    right--;
                }else if (sum < -nums[i]) {
                    left++;
                }else {
                    ret.add(new ArrayList<Integer>(Arrays.asList(nums[i],nums[left],nums[right])));
                    //去重1
                    left++;
                    right--;

                    while (left < right && nums[left] == nums[left-1]) left++;

                    while (left < right && nums[right] == nums[right+1])right--;
                }

            }
            //去重2
            i++;
            while (i < nums.length  && nums[i] == nums[i-1])i++;
        }
        return ret;


    }

    public static void main(String[] args) {
        Solution alg1 = new Solution();
        int[] arrys = {-1 , 0 , 1 ,2 , -1 ,-4};
        List<List<Integer>> eas = alg1.threeSum(arrys);
        System.out.println(eas);
    }

}
